package com.slashvision.im.chat

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Divider
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.insets.imePadding
import com.google.accompanist.insets.navigationBarsWithImePadding
import com.slashvision.im.R
import com.slashvision.im.SLog
import com.slashvision.im.ui.RoundedCornerButton
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.models.Message
import kotlin.math.abs

/**
 * author : lizhenxin
 *  date  : 2021/11/16
 *  desc  :
 */
/**
 * @desc:
 * @author: LiZhenxin
 * @create:
 * update
 **/

const val TAG_IM_VOICE = "_TAG_IM_VOICE_"

sealed class InputSelector
object SelectorText : InputSelector()
object SelectorVoice : InputSelector()
object SelectorEmoji : InputSelector()
object SelectorExpand : InputSelector()

sealed class InputType
object TypeText : InputType()
object TypeVoice : InputType()


@ExperimentalComposeUiApi
@Composable
fun UserInput(
    modifier: Modifier = Modifier,
    onSendText: (String) -> Unit,
    voiceLongPressListener: VoiceOnLongPressListener
) {
    // 当前输入方式
    val inputSelectorState = remember { mutableStateOf<InputSelector>(SelectorText) }

    // 软键盘控制器
    val imeController = LocalSoftwareKeyboardController.current

    // 输入的文字
    val textInputContentState = remember { mutableStateOf("") }

    // 切换语音输入和文字输入
    val inputTypeState = remember { mutableStateOf<InputType>(TypeText) }

    // 文本输入框焦点控制器
    val textFocusManager = LocalFocusManager.current

    Column(modifier = modifier.fillMaxWidth()) {
        Divider(color = colorResource(id = R.color.toolbar_spacer), thickness = 1.dp)
        // 输入栏

        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp)
        ) {
            // 切换输入方式按钮
            Image(
                painter = painterResource(
                    id = if (inputTypeState.value == TypeText) {
                        R.drawable.ic_keybored
                    } else R.drawable.ic_sound
                ),
                contentDescription = null,
                modifier = Modifier
                    .size(26.dp)
                    .clickable {
                        if (inputTypeState.value == TypeText) {
                            inputTypeState.value = TypeVoice
                            inputSelectorState.value = SelectorVoice
                        } else {
                            inputTypeState.value = TypeText
                            inputSelectorState.value = SelectorText
                        }
                    }
            )

            // 输入区域
            Row(
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 12.dp)
                    .background(
                        color = colorResource(id = R.color.color_f7),
                        shape = RoundedCornerShape(50)
                    )
            ) {
                if (inputTypeState.value == TypeText) {
                    TextInput(
                        textInputContent = textInputContentState,
                        onFocusChange = {
                            if (true) {
                                inputSelectorState.value = SelectorText
                            } else {

                            }
                        },
                        onEmojiInputClick = {
                            textFocusManager.clearFocus(true)
                            inputSelectorState.value = SelectorEmoji
                        })
                } else {
                    VoiceInput(
                        modifier = Modifier,
                        longPressListener = voiceLongPressListener
                    )
                }
            }
            /**
             * 发送区域
             */

            SendArea(
                isSend = inputTypeState.value == TypeText && textInputContentState.value.isNotEmpty(),
                onSendClick = {
                    textInputContentState.value.takeIf { it.isNotEmpty() }?.let{ onSendText(it) }
                    textInputContentState.value = ""
                },
                onExpandClick = {
                    textFocusManager.clearFocus(true)
                    inputSelectorState.value = SelectorExpand
                }
            )
        }

        // 不同输入方式对应的ui
        inputSelectorState.value.let {
            when (it) {
                is SelectorText -> {
                    imeController?.show()
                }
                is SelectorVoice -> {
                    imeController?.hide()
                }
                is SelectorEmoji -> {
                    imeController?.hide()
                    EmojiTable {
                        textInputContentState.value = textInputContentState.value.plus(it)
                    }
                }
                is SelectorExpand -> {
                    imeController?.hide()
                    ExpandInput()
                }
            }
        }

        Spacer(modifier = Modifier.navigationBarsWithImePadding())
    }
}


@Composable
fun TextInput(
    textInputContent: MutableState<String>,
    onFocusChange: (Boolean) -> Unit,
    onEmojiInputClick: () -> Unit
) = Row(
    verticalAlignment = Alignment.CenterVertically
) {
    Spacer(modifier = Modifier.width(15.dp))
    // 文字输入
    BasicTextField(
        value = textInputContent.value,
        onValueChange = {
            textInputContent.value = it
        },
        maxLines = 5,
        textStyle = TextStyle(
            color = colorResource(id = R.color.black_3),
            fontSize = 14.sp
        ),
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Text,
            imeAction = ImeAction.Send
        ),
        modifier = Modifier
            .weight(1f)
            .padding(vertical = 11.dp)
            .clickable {
                onFocusChange(true)
            }
            .onFocusChanged {
                onFocusChange(it.hasFocus)
            }
    )
    Spacer(modifier = Modifier.width(15.dp))
    // 表情输入
    Image(
        painter = painterResource(id = R.drawable.ic_expression),
        contentDescription = null,
        modifier = Modifier
            .size(26.dp)
            .clickable { onEmojiInputClick() }
    )
    Spacer(modifier = Modifier.width(15.dp))
}


@Composable
fun VoiceInput(
    modifier: Modifier,
    longPressListener: VoiceOnLongPressListener
) = Text(
    text = "按住说话",
    fontSize = 14.sp,
    color = colorResource(id = R.color.black_3),
    fontWeight = FontWeight.Medium,
    textAlign = TextAlign.Center,
    modifier = modifier
        .fillMaxWidth()
        .padding(vertical = 11.dp)
        .pointerInput(Unit) {
            detectDragGesturesAfterLongPress(
                onDrag = { change: PointerInputChange, dragAmount: Offset ->
                    // change.position: 相对view的位置
                    SLog.d(
                        TAG_IM_VOICE,
                        "current: (${change.position.x},${change.position.y})"
                    )
                    // 上滑距离超过一百则为越界。
                    // 如果需要判断是否在indicator内，则利用
                    if (abs(change.position.y) > 100) {
                        longPressListener.onMoveOutside(true)
                    } else {
                        longPressListener.onMoveOutside(false)
                    }
                },
                onDragStart = {
                    longPressListener.onStartLongPress(it)
                    SLog.d(TAG_IM_VOICE, "长按开始拖动: (${it.x},${it.y})")
                },
                onDragEnd = {
                    longPressListener.onStopLongPress()
                    SLog.d(TAG_IM_VOICE, "长按结束拖动")
                }
            )
        }
)


@Composable
fun SendArea(
    isSend: Boolean,
    onSendClick: () -> Unit,
    onExpandClick: () -> Unit
) {
    if (isSend) {
        RoundedCornerButton(
            text = "发送",
            textSize = 14.sp,
            textColor = colorResource(id = R.color.white),
            bacColor = colorResource(id = R.color.main_blue),
            contentPadding = PaddingValues(vertical = 7.dp, horizontal = 13.dp)
        ) {
            onSendClick()

        }
    } else {
        Image(
            painter = painterResource(id = R.drawable.ic_add_more),
            contentDescription = null,
            modifier = Modifier
                .size(26.dp)
                .clickable {
                    onExpandClick()
                }
        )
    }
}


@Composable
fun ExpandInput() = Row(
    modifier = Modifier
        .fillMaxWidth()
        .padding(horizontal = 22.dp)
) {
    ChatViewModel.extentInputList.forEach {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier
                .padding(start = 11.dp, end = 11.dp, top = 22.dp, bottom = 34.dp)
                .clickable { it.clickEvent() }
        ) {
            Image(
                painter = painterResource(id = it.imgIdRes),
                contentDescription = it.name,
                modifier = Modifier
                    .size(56.dp)
            )
            Spacer(modifier = Modifier.size(10.dp))
            Text(
                text = it.name,
                fontSize = 12.sp,
                color = colorResource(id = R.color.black_3),
            )
        }
    }
}

@Composable
fun EmojiTable(
    modifier: Modifier = Modifier,
    onEmojiClick: (String) -> Unit
) {
    Column(modifier.fillMaxWidth()) {
        repeat(4) { x ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                repeat(EMOJI_COLUMNS) { y ->
                    val emoji = emojis[x * EMOJI_COLUMNS + y]
                    Text(
                        modifier = Modifier
                            .clickable(onClick = { onEmojiClick(emoji) })
                            .sizeIn(minWidth = 42.dp, minHeight = 42.dp)
                            .padding(8.dp),
                        text = emoji,
                        style = LocalTextStyle.current.copy(
                            fontSize = 18.sp,
                            textAlign = TextAlign.Center
                        )
                    )
                }
            }
        }
    }
}


interface VoiceOnLongPressListener {
    fun onStartLongPress(offset: Offset)
    fun onMoveOutside(isOutside: Boolean)
    fun onStopLongPress()
}


/**
 * 在此处初始化：
 * @see com.slashvision.imActivity.initExtendInputItem
 */


private const val EMOJI_COLUMNS = 10

private val emojis = listOf(
    "\ud83d\ude00", // Grinning Face
    "\ud83d\ude01", // Grinning Face With Smiling Eyes
    "\ud83d\ude02", // Face With Tears of Joy
    "\ud83d\ude03", // Smiling Face With Open Mouth
    "\ud83d\ude04", // Smiling Face With Open Mouth and Smiling Eyes
    "\ud83d\ude05", // Smiling Face With Open Mouth and Cold Sweat
    "\ud83d\ude06", // Smiling Face With Open Mouth and Tightly-Closed Eyes
    "\ud83d\ude09", // Winking Face
    "\ud83d\ude0a", // Smiling Face With Smiling Eyes
    "\ud83d\ude0b", // Face Savouring Delicious Food
    "\ud83d\ude0e", // Smiling Face With Sunglasses
    "\ud83d\ude0d", // Smiling Face With Heart-Shaped Eyes
    "\ud83d\ude18", // Face Throwing a Kiss
    "\ud83d\ude17", // Kissing Face
    "\ud83d\ude19", // Kissing Face With Smiling Eyes
    "\ud83d\ude1a", // Kissing Face With Closed Eyes
    "\u263a", // White Smiling Face
    "\ud83d\ude42", // Slightly Smiling Face
    "\ud83e\udd17", // Hugging Face
    "\ud83d\ude07", // Smiling Face With Halo
    "\ud83e\udd13", // Nerd Face
    "\ud83e\udd14", // Thinking Face
    "\ud83d\ude10", // Neutral Face
    "\ud83d\ude11", // Expressionless Face
    "\ud83d\ude36", // Face Without Mouth
    "\ud83d\ude44", // Face With Rolling Eyes
    "\ud83d\ude0f", // Smirking Face
    "\ud83d\ude23", // Persevering Face
    "\ud83d\ude25", // Disappointed but Relieved Face
    "\ud83d\ude2e", // Face With Open Mouth
    "\ud83e\udd10", // Zipper-Mouth Face
    "\ud83d\ude2f", // Hushed Face
    "\ud83d\ude2a", // Sleepy Face
    "\ud83d\ude2b", // Tired Face
    "\ud83d\ude34", // Sleeping Face
    "\ud83d\ude0c", // Relieved Face
    "\ud83d\ude1b", // Face With Stuck-Out Tongue
    "\ud83d\ude1c", // Face With Stuck-Out Tongue and Winking Eye
    "\ud83d\ude1d", // Face With Stuck-Out Tongue and Tightly-Closed Eyes
    "\ud83d\ude12", // Unamused Face
    "\ud83d\ude13", // Face With Cold Sweat
    "\ud83d\ude14", // Pensive Face
    "\ud83d\ude15", // Confused Face
    "\ud83d\ude43", // Upside-Down Face
    "\ud83e\udd11", // Money-Mouth Face
    "\ud83d\ude32", // Astonished Face
    "\ud83d\ude37", // Face With Medical Mask
    "\ud83e\udd12", // Face With Thermometer
    "\ud83e\udd15", // Face With Head-Bandage
    "\u2639", // White Frowning Face
    "\ud83d\ude41", // Slightly Frowning Face
    "\ud83d\ude16", // Confounded Face
    "\ud83d\ude1e", // Disappointed Face
    "\ud83d\ude1f", // Worried Face
    "\ud83d\ude24", // Face With Look of Triumph
    "\ud83d\ude22", // Crying Face
    "\ud83d\ude2d", // Loudly Crying Face
    "\ud83d\ude26", // Frowning Face With Open Mouth
    "\ud83d\ude27", // Anguished Face
    "\ud83d\ude28", // Fearful Face
    "\ud83d\ude29", // Weary Face
    "\ud83d\ude2c", // Grimacing Face
    "\ud83d\ude30", // Face With Open Mouth and Cold Sweat
    "\ud83d\ude31", // Face Screaming in Fear
    "\ud83d\ude33", // Flushed Face
    "\ud83d\ude35", // Dizzy Face
    "\ud83d\ude21", // Pouting Face
    "\ud83d\ude20", // Angry Face
    "\ud83d\ude08", // Smiling Face With Horns
    "\ud83d\udc7f", // Imp
    "\ud83d\udc79", // Japanese Ogre
    "\ud83d\udc7a", // Japanese Goblin
    "\ud83d\udc80", // Skull
    "\ud83d\udc7b", // Ghost
    "\ud83d\udc7d", // Extraterrestrial Alien
    "\ud83e\udd16", // Robot Face
    "\ud83d\udca9", // Pile of Poo
    "\ud83d\ude3a", // Smiling Cat Face With Open Mouth
    "\ud83d\ude38", // Grinning Cat Face With Smiling Eyes
    "\ud83d\ude39", // Cat Face With Tears of Joy
    "\ud83d\ude3b", // Smiling Cat Face With Heart-Shaped Eyes
    "\ud83d\ude3c", // Cat Face With Wry Smile
    "\ud83d\ude3d", // Kissing Cat Face With Closed Eyes
    "\ud83d\ude40", // Weary Cat Face
    "\ud83d\ude3f", // Crying Cat Face
    "\ud83d\ude3e", // Pouting Cat Face
    "\ud83d\udc66", // Boy
    "\ud83d\udc67", // Girl
    "\ud83d\udc68", // Man
    "\ud83d\udc69", // Woman
    "\ud83d\udc74", // Older Man
    "\ud83d\udc75", // Older Woman
    "\ud83d\udc76", // Baby
    "\ud83d\udc71", // Person With Blond Hair
    "\ud83d\udc6e", // Police Officer
    "\ud83d\udc72", // Man With Gua Pi Mao
    "\ud83d\udc73", // Man With Turban
    "\ud83d\udc77", // Construction Worker
    "\u26d1", // Helmet With White Cross
    "\ud83d\udc78", // Princess
    "\ud83d\udc82", // Guardsman
    "\ud83d\udd75", // Sleuth or Spy
    "\ud83c\udf85", // Father Christmas
    "\ud83d\udc70", // Bride With Veil
    "\ud83d\udc7c", // Baby Angel
    "\ud83d\udc86", // Face Massage
    "\ud83d\udc87", // Haircut
    "\ud83d\ude4d", // Person Frowning
    "\ud83d\ude4e", // Person With Pouting Face
    "\ud83d\ude45", // Face With No Good Gesture
    "\ud83d\ude46", // Face With OK Gesture
    "\ud83d\udc81", // Information Desk Person
    "\ud83d\ude4b", // Happy Person Raising One Hand
    "\ud83d\ude47", // Person Bowing Deeply
    "\ud83d\ude4c", // Person Raising Both Hands in Celebration
    "\ud83d\ude4f", // Person With Folded Hands
    "\ud83d\udde3", // Speaking Head in Silhouette
    "\ud83d\udc64", // Bust in Silhouette
    "\ud83d\udc65", // Busts in Silhouette
    "\ud83d\udeb6", // Pedestrian
    "\ud83c\udfc3", // Runner
    "\ud83d\udc6f", // Woman With Bunny Ears
    "\ud83d\udc83", // Dancer
    "\ud83d\udd74", // Man in Business Suit Levitating
    "\ud83d\udc6b", // Man and Woman Holding Hands
    "\ud83d\udc6c", // Two Men Holding Hands
    "\ud83d\udc6d", // Two Women Holding Hands
    "\ud83d\udc8f" // Kiss
)